package com.example.poemtest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.poemtest.Activity.BottomNavigationViewActivity;
import com.example.poemtest.Activity.LoginActivity;
import com.example.poemtest.entity.DynastyToUserBean;
import com.example.poemtest.entity.PoetryInfoBean;
import com.example.poemtest.entity.PostInfoBean;
import com.example.poemtest.entity.StudyPoetryBean;
import com.example.poemtest.entity.UserInfoBean;
import com.example.poemtest.entity.VideoPoetryBean;
import com.example.poemtest.index.activity.FlyFlowerOrderActivity;
import com.example.poemtest.index.activity.PoetryAdmireActivity;
import com.example.poemtest.index.activity.PoetryRelayActivity;
import com.example.poemtest.index.activity.PoetryVideoActivity;
import com.example.poemtest.index.activity.SearchActivity;
import com.example.poemtest.index.activity.StudyActivity;
import com.example.poemtest.index.activity.TakeExamActivity;
import com.example.poemtest.index.activity.WritePoetryActivity;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * created by JHT on 2024/3/13
 * 首页页面fragment
 */
public class IndexFragment extends Fragment implements View.OnClickListener {
    private View root;
//    private static final int REQ_CODE_UPDATE_SCENE_KIT = 10001;
//    private static final int RES_CODE_UPDATE_SUCCESS = -1;
    private static final String TAG="IndexFragment";

    private boolean initialized = false;

    private ImageButton shicijianshang, shicidahui, lingganchuangzuo, zicishiyi, kaoyikao, chengyujielong
            , shicijielong, feihualing, xiaochugao;
    private ImageView search;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    public static final int RESEND = 1, SEND = 2, SUCCESS = 3, CODEFALSE = 4, FALSE = 5;  //常量值
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            int flag = msg.arg1;
            if (flag == 0) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        DynastyToUserBean dynastyToUserBeans = com.alibaba.fastjson.JSONObject.parseObject(result,DynastyToUserBean.class);
                        List<DynastyToUserBean.DynastyToUser> list = dynastyToUserBeans.getData();
//                    if (Constant.userPoetryDynastyList.size() != 0) {
//                        Constant.userPoetryDynastyList.clear();
//                    }
                        for (DynastyToUserBean.DynastyToUser dynasty : list) {
                            Constant.userPoetryDynastyList.add((Integer) dynasty.getNum());
                            Log.e("数字",dynasty.getNum() + "");
                        }
                    } else {
//                    Toast.makeText(LoginActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 1) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        VideoPoetryBean videoPoetryBean = com.alibaba.fastjson.JSONObject.parseObject(result, VideoPoetryBean.class);
                        List<VideoPoetryBean.VideoPoetry> list = videoPoetryBean.getData();
                        for (VideoPoetryBean.VideoPoetry videoPoetry : list) {
                            Constant.videoPoetries.add(videoPoetry);
                        }
                    } else {
//                    Toast.makeText(LoginActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 2) {
                Log.e("flag=",flag + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PostInfoBean postInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PostInfoBean.class);
                        List<PostInfoBean.PostInfo> list = postInfoBean.getData();
                        if (Constant.postList.size() != 0) {
                            Constant.postList.clear();
                        }
                        for (PostInfoBean.PostInfo postInfo : list) {
                            Constant.postList.add(postInfo);
                        }
                        //打印一下信息
                        for (PostInfoBean.PostInfo postInfo : Constant.postList) {
                            Log.e("我创建的词帖",postInfo.toString());
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 3) {
                Log.e("flag=",flag + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        StudyPoetryBean studyPoetryBean = com.alibaba.fastjson.JSONObject.parseObject(result,StudyPoetryBean.class);
                        List<StudyPoetryBean.StudyPoetry> list = studyPoetryBean.getData();
                        if (Constant.studyPoetries.size() != 0) {
                            Constant.studyPoetries.clear();
                        }
                        for (StudyPoetryBean.StudyPoetry studyPoetry : list) {
                            Constant.studyPoetries.add(studyPoetry);
                        }
                        //打印一下信息
                        for (PostInfoBean.PostInfo postInfo : Constant.postList) {
                            Log.e("我创建的词帖",postInfo.toString());
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 4) {
                Log.e("flag=",flag + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PoetryInfoBean poetryInfo = com.alibaba.fastjson.JSONObject.parseObject(result,PoetryInfoBean.class);
                        List<PoetryInfoBean.PoetryInfo> list = poetryInfo.getData();
//                        if (Constant.poetryInfos.size() != 0) {
//                            Constant.poetryInfos.clear();
//                        }
                        for (PoetryInfoBean.PoetryInfo poetryInfo1 : list) {
                            Constant.poetryInfos.add(poetryInfo1);
                        }
                        //打印一下信息
                        for (PoetryInfoBean.PoetryInfo postInfo : Constant.poetryInfos) {
                            Log.e("飞花令",postInfo.toString());
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        FullScreenUtil.getInstance().fullScreen(getActivity(),true);
        root = inflater.inflate(R.layout.fragment_index,container,false);
        setView();
        //查询已经解锁的朝代信息
        getCoon();
        //查询所有的诗词大会的数据
        getCoon1();
        //查询所有的词帖信息
        getCoon2();
        //获取小初高的诗词信息
        getCoon3();
        //获取飞花令和诗词接龙的诗词信息
        getCoon4();
//        root.setBackgroundResource(R.mipmap.index_bg);
        return root;
    }

    private void setView() {
        root.setBackgroundResource(R.mipmap.index_bg);
        shicijianshang = root.findViewById(R.id.shicijianshang);
        shicijianshang.setOnClickListener(this);
        shicidahui = root.findViewById(R.id.shicidahui);
        shicidahui.setOnClickListener(this);
        lingganchuangzuo = root.findViewById(R.id.lingganchuangzuo);
        lingganchuangzuo.setOnClickListener(this);
        kaoyikao = root.findViewById(R.id.kaoyikao);
        kaoyikao.setOnClickListener(this);
        shicijielong = root.findViewById(R.id.shicijielong);
        shicijielong.setOnClickListener(this);
        feihualing = root.findViewById(R.id.feihualing);
        feihualing.setOnClickListener(this);
        xiaochugao = root.findViewById(R.id.xiaochugao);
        xiaochugao.setOnClickListener(this);
        search = root.findViewById(R.id.search);
        search.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search:
                Log.e(TAG,"搜索");
                Intent intent3 = new Intent(IndexFragment.this.getActivity(), SearchActivity.class);
                startActivity(intent3);
                break;
            case R.id.shicijianshang:
                Log.e(TAG,"诗词鉴赏");
                Intent intent = new Intent(IndexFragment.this.getActivity(), PoetryAdmireActivity.class);
                startActivity(intent);
                break;
            case R.id.shicidahui:
                Log.e("msg","诗词大会");
                //跳转到诗词大会视频的页面
                Intent intent1 = new Intent(IndexFragment.this.getActivity(), PoetryVideoActivity.class);
                startActivity(intent1);
                break;
            case R.id.lingganchuangzuo:
                Log.e("msg","灵感创作");
                Intent intent2 = new Intent(IndexFragment.this.getActivity(), WritePoetryActivity.class);
                startActivity(intent2);
                break;
            case R.id.kaoyikao:
                Log.e("msg","考一考");
                startActivity(new Intent(getActivity(), TakeExamActivity.class));
                break;
            case R.id.shicijielong:
                Log.e("msg","诗词接龙");
                PoetryRelayActivity.start(getActivity());
                break;
            case R.id.feihualing:
                Log.e("msg","飞花令");
                FlyFlowerOrderActivity.start(getActivity());
                break;
            case R.id.xiaochugao:
                Log.e("msg","小初高");
                Intent intent8 = new Intent(IndexFragment.this.getActivity(), StudyActivity.class);
                startActivity(intent8);
                break;
            default:
                break;
        }
    }

    /**
     * 获取网络连接
     */
    private void getCoon(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/myDynasty/findDynasty?userId=" + Constant.userId)        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 0;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取诗词大会视频的数据
     */
    private void getCoon1(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/videoPoetry/findAll")        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 1;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取所有的词帖的信息
     */
    private void getCoon2(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/postInfo/findAll")        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 2;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取所有的小初高的诗词
     */
    private void getCoon3(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/studyPoetry/findAll")        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 3;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取飞花令和诗词接龙的信息
     */
    private void getCoon4(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/poetryInfo/findPoetryAll")        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 4;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}
